package com.ailanyin.modules.im.server;

import com.ailanyin.modules.im.security.WebsocketSecurity;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 核心消息处理
 *
 * @author ailanyin
 * @version 1.0
 * @since 2022/11/30 0030 上午 10:55
 */
@ServerEndpoint("/websocket/{username}/{token}")
@Component
public class ImServer {

    private static WebsocketSecurity websocketSecurity = new WebsocketSecurity();
    private static final ConcurrentHashMap<String, Session> SESSION_POOL = new ConcurrentHashMap();

    /**
     * 建立连接
     *
     * @param username username
     * @param token    token
     * @param session  session
     */
    @OnOpen
    public void onOpen(@PathParam("username") String username,
                       @PathParam("token") String token,
                       Session session) {
        websocketSecurity.checkSecurity(token);
        SESSION_POOL.put(username, session);
    }

    /**
     * 关闭连接
     *
     * @param username username
     */
    @OnClose
    public void onClose(@PathParam("username") String username) {
        SESSION_POOL.remove(username);
    }

    /**
     * 收到消息
     *
     * @param username username
     * @param message  message
     */
    @OnMessage
    public void onMessage(@PathParam("username") String username, String message) {
        System.out.println("用户: " + username + " 说: " + message);
        sendMessage(username);
    }

    public void sendMessage(String username) {
        if (SESSION_POOL.get(username) == null) {
            return;
        }
        try {
            SESSION_POOL.get(username).getBasicRemote().sendText("TEST WEBSOCKET SUCCESS");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
